package com.summer.bilibili.validator.db;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.summer.bilibili.util.SecurityUtils;


import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.List;

/**
 * 校验一个对象值（如字段值）是否在指定的数据库表中存在
 */
public class DBExistsValidator implements ConstraintValidator < DBExists, Object > {
    private DBExists instance;
    private String keyColumn;
    private String userIdColumn;
    private List < String > ignores;

    @Override
    public void initialize ( DBExists constraintAnnotation ) {
        instance = constraintAnnotation;
        // 解析主键列
        this.keyColumn = instance.keyColumn ( );
        if ( StrUtil.isBlank ( keyColumn ) ) {
            this.keyColumn = TableInfoHelper.getTableInfo ( instance.value ( ) ).getKeyColumn ( );
            if ( keyColumn == null ) {
                throw new RuntimeException ( "无法找到 " + instance.value ( ) + " 的主键" );
            }
        }
        // 初始化其他配置
        this.userIdColumn = instance.userIdColumn ( );
        this.ignores = Arrays.asList ( constraintAnnotation.ignores ( ) );
    }

    @Override
    public boolean isValid ( Object value , ConstraintValidatorContext context ) {
        // 忽略检查
        if ( value != null && !ignores.contains ( value.toString ( ) ) ) {
            // 获取当前用户ID
            Long contextUserId = SecurityUtils.getContextUserId ( false );
            // 构建查询并执行
            boolean result = Db.query ( instance.value ( ) )
                    .eq ( keyColumn , value )
                    .eq ( instance.checkUserId ( ) , userIdColumn , contextUserId )
                    .exists ( );
            // 结果判定
            return instance.errorInExist ( ) != result;
        }
        return true;
    }
}
